<?php
namespace Inbound\Controller;
use \Home\Controller\CommonController;
use Inbound\Service\PublicInfoService;

class VirtualFbaController extends CommonController {

    public $virtualFbaService = null;
    public $prepareneedsService = null;
    public $inboundshipmentplanService = null;
    public $transferHopperAddress = null;
    public $inventory = null;
    public $warehouseOrderService = NULL;
    
    public function __construct() {
        $this->virtualFbaService = D('VirtualFba', 'Service');
        $this->prepareneedsService = D('Prepareneeds', 'Service');
        $this->inboundshipmentplanService = D('Inboundshipmentplan', 'Service');
        $this->transferHopperAddress = D('TransferHopperAddress','Service');
        $this->inventory = D('Warehouse/Inventory', 'Service');
        $this->warehouseOrderService = D('Warehouse/StockIn', 'Service');
        parent::__construct();
    }
    /**
     * 备货申请
     */
    public function prepare() {
        $sites = array();
        
/*         if (isset($_SESSION['current_account']) && !empty($_SESSION['current_account'])) {
            if (in_array($_SESSION['current_account']['role_id'], array(3,4))) {
                $accounts = PublicInfoService::salesmanBindAccountsGet($_SESSION['current_account']['id']);
                
                foreach ($accounts as $acc) {
                    $sites[$acc['id']] = $acc['shorthand_code'];
                }
                
                $this->assign('accounts', $accounts);
                $this->assign('sites', $sites);
            } else {
                if ($_GET['accountId']) {
                    $this->assign('accountId', $_GET['accountId']);
                } else {
                    $this->assign('accountId', 0);
                }
                $this->assign('accounts', PublicInfoService::get_accounts());
            }
        } */
        if ($_GET['accountId']) {
            $this->assign('accountId', $_GET['accountId']);
        } else {
            $this->assign('accountId', 0);
        }
        $accounts = $this->virtualFbaService->getAllStore();
        $this->assign('accounts', $accounts);
        $address = $this->transferHopperAddress->getTransferHopperAddress();
        $this->assign('address', $address);
        $this->assign('enterprise_dominant', PublicInfoService::get_company_array());
        
        $this->display();
    }
    /**
     *描述:根据关键词获取SKU列表
     */
    public function skuAutoComplete() {
        $re = array();
        
        $skus = PublicInfoService::accountSkuGet($_GET['accountId'], $_GET['skuKeywords']);
        
        if(!empty($skus)) {
            foreach ($skus as $sku) {
                $re[] = array(
                    'label' => $sku,
                    'sku' => $sku
                );
            }
        }
        unset($skus);
        
        echo json_encode($re);
        exit;
    }
    /**
     * 描述:根据SKU获取SKU产品名称
     */
    public function skuInfoGet() {
        $skuInfo = array();
        
        $skuTile = PublicInfoService::accountSkuTitleGet($_GET['sku']);
        $skuInfo['name'] = $skuTile;
        
        echo json_encode($skuInfo);
        exit;
    }
    /**
     * 描述：检查最终输入的SKU是否存在
     */
    public function skuCheck() {
        $sku = array();
        $skuKeywords = trim($_GET['skuKeywords']);
        $sku['sku'] = $this->virtualFbaService->checkSku($skuKeywords);
        $sku['name'] = PublicInfoService::accountSkuTitleGet($skuKeywords);

        echo json_encode($sku);
        exit;
    }
    
    /**
     * 描述：根据SKU获取实际库存、实际可用库存
     */
    public function skuInventoryGet() {
        $skuInventoryInfo = array();
        
        if ($_GET['sku']) {
            //$site_id = PublicInfoService::get_siteid_by_accountid($_GET['account_id']);
            $site_id = $this->virtualFbaService->getAttrById(trim($_GET['account_id']));
            $condition = array('sku' => trim($_GET['sku']),
                'export_tax_rebate' => $_GET['export_tax_rebate'],
                'enterprise_dominant' => trim($_GET['enterprise_dominant']),
                'site_id' => $site_id
            );
            if ($_GET['export_tax_rebate']) {
                $quantity= $this->inventory->getTaxInventoriesInfo($condition);
                $skuInventoryInfo['quantity'] = $quantity['stock'] ? $quantity['stock'] : 0;
                $skuInventoryInfo['actualQuantity'] =
                $quantity['actual_available_num'] ? $quantity['actual_available_num'] : 0;
                $skuInventoryInfo['totalActualQuantity'] =
                $quantity['all_site_num'] ? $quantity['all_site_num'] : 0;
            } else {
                $quantity= $this->inventory->getInventoriesInfo($condition);
                $skuInventoryInfo['quantity'] = $quantity['stock'] ? $quantity['stock'] : 0;
                $skuInventoryInfo['actualQuantity'] =
                $quantity['actual_available_num'] ? $quantity['actual_available_num'] : 0;
                $skuInventoryInfo['totalActualQuantity'] =
                $quantity['all_site_num'] ? $quantity['all_site_num'] : 0;
            }
            
            $occupiedStockingNeedInventory = $this->prepareneedsService->occupiedStockingNeedInventoryGet($_GET);
            $occupiedInventory = $this->inboundshipmentplanService->occupiedInventoryGet($_GET);
            
            $occupyQuantity = 0;
            if (!empty($occupiedStockingNeedInventory)) {
                foreach ($occupiedStockingNeedInventory as $value) {
                    $occupyQuantity += $value['quantity'];
                }
            }
            if (!empty($occupiedInventory)) {
                foreach ($occupiedInventory as $value) {
                    $occupyQuantity += $value['quantity'];
                }
            }
            $skuInventoryInfo['occupyQuantity'] = $occupyQuantity;
        }
        
        echo json_encode($skuInventoryInfo);
    }
    public function checkWarehouseOrder() {
        if ($_GET['sku'] && $_GET['enterprise_dominant']) {
            $returnMsg = $this->warehouseOrderService->checkWarehouseOrder($_GET);
            
            echo json_encode($returnMsg);
            exit;
        }
    }
    
    /**
     * 描述：把前台界面的备货申请插入数据库中
     */
    public function stockingApplyInsert() {
        $stockingApplyData = json_decode($_POST['data'], true);
        $moveMessage = '';
        foreach ($stockingApplyData as $key => &$data) {
            $data['sku'] = trim($data['sku']);
            $data['needs_quantity'] = trim($data['needs_quantity']);
            $data['claim_arrive_time'] = trim($data['claim_arrive_time']);
            $data['site_id'] = $this->virtualFbaService->getAttrById(trim($data['account_id']));
            $data['account_name'] = $this->virtualFbaService->getAttrById(trim($data['account_id']),'accName');
            
            $condition = array('sku' => $data['sku'],
                'export_tax_rebate' => $data['export_tax_rebate'],
                'enterprise_dominant' => $data['enterprise_dominant'],
                'site_id' => $data['site_id']
            );
            
            if ($data['export_tax_rebate']) {
                $quantity= $this->inventory->getTaxInventoriesInfo($condition);
            } else {
                $quantity= $this->inventory->getInventoriesInfo($condition);
            }
            
            if ($data['needs_quantity'] > $quantity['actual_available_num']) {
                $condition = array(
                    'sku' => $data['sku'],
                    'enterprise_dominant' => $data['enterprise_dominant'],
                    'export_tax_rebate' => $data['export_tax_rebate'],
                    'site_id' => $data['site_id'],
                    'quantity' => $data['needs_quantity']
                );
                
                $result = $this->inventory->auto_move_site($condition);
                if (!$result['status']) {
                    $moveMessage .=  '[' . $data['sku'] . ']:' . $result['message'];
                    unset($stockingApplyData[$key]);
                    continue;
                };
            }
            
            $data['status'] = (isset($_SESSION['current_account']) && !empty($_SESSION['current_account'])
                && in_array($_SESSION['current_account']['role_id'], array(3,4))) ? 20 : 10;
                
                isset($_SESSION['current_account']) && !empty($_SESSION['current_account'])
                && in_array($_SESSION['current_account']['role_id'], array(5))
                && $data['buyer_id'] = $_SESSION['current_account']['id'];
                
                $skuCnname = PublicInfoService::getSkuCnname($data['sku']);
                $data['hs_code'] = $skuCnname['hs_code'];
                
                $data['create_user_id'] = $_SESSION['current_account']['id'];
                $data['create_time'] = date("Y-m-d H:i:s");
        }
        
        if (!empty($stockingApplyData)) {
            $result = $this->prepareneedsService->stockingApplyInsert($stockingApplyData);
            if ($moveMessage) {
                $result['message'] .= $moveMessage;
            }
            
            echo json_encode($result);
        } else {
            $result = array(
                'status' => 0,
                'message' => $moveMessage
            );
            
            echo json_encode($result);
        }
    }
}